<?php
session_start();
require_once '../classes/Database.php';
require_once '../classes/ProductManager.php';
require_once '../classes/CDKManager.php';
require_once '../classes/SettingsHelper.php';

// 检查管理员登录
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$productManager = new ProductManager();
$cdkManager = new CDKManager();

// 处理添加商品
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add_product') {
        $name = $_POST['name'] ?? '';
        $description = $_POST['description'] ?? '';
        $price = $_POST['price'] ?? 0;
        $stock = $_POST['stock'] ?? 0;
        
        if ($productManager->addProduct($name, $description, $price, $stock)) {
            $success = "商品添加成功";
        } else {
            $error = "商品添加失败";
        }
    }
    
    // 处理编辑商品
    if ($_POST['action'] === 'edit_product') {
        $id = $_POST['id'] ?? 0;
        $name = $_POST['name'] ?? '';
        $description = $_POST['description'] ?? '';
        $price = $_POST['price'] ?? 0;
        $stock = $_POST['stock'] ?? 0;
        $status = $_POST['status'] ?? 1;
        
        if ($productManager->updateProduct($id, $name, $description, $price, $stock, $status)) {
            $success = "商品更新成功";
        } else {
            $error = "商品更新失败";
        }
    }
    
    // 处理删除商品
    if ($_POST['action'] === 'delete_product') {
        $id = $_POST['id'] ?? 0;
        if ($productManager->deleteProduct($id)) {
            $success = "商品删除成功";
        } else {
            $error = "商品删除失败";
        }
    }
    
    // 处理批量生成CDK
    if ($_POST['action'] === 'generate_cdks') {
        $productId = $_POST['product_id'] ?? 0;
        $count = $_POST['count'] ?? 1;
        
        $generated = 0;
        for ($i = 0; $i < $count; $i++) {
            if ($cdkManager->addCDK($productId)) {
                $generated++;
            }
        }
        
        if ($generated > 0) {
            $success = "成功生成 {$generated} 个CDK码";
        } else {
            $error = "CDK码生成失败";
        }
    }
}

// 获取商品列表
$products = $productManager->getAllProducts();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品管理 - <?php echo htmlspecialchars(getSiteName()); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="assets/admin.css" rel="stylesheet">
    <style>
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); }
        .modal-content { background: white; margin: 5% auto; padding: 20px; border-radius: 5px; width: 500px; max-width: 95%; }
    </style>
</head>
<body>
    <!-- 顶部导航栏（移动端显示） -->
    <div class="top-navbar d-flex align-items-center justify-content-between">
        <button class="sidebar-toggle">
            <i class="fas fa-bars"></i>
        </button>
        <h5 class="mb-0">商品管理 - <?php echo htmlspecialchars(getSiteName()); ?></h5>
        <div class="text-muted small">
            <i class="fas fa-user me-1"></i><?php echo htmlspecialchars($_SESSION['admin_username']); ?>
        </div>
    </div>

    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h4 class="mb-3">
                <i class="fas fa-cogs me-2"></i><span><?php echo htmlspecialchars(getSiteName()); ?></span>
            </h4>
            <p class="text-muted mb-0 small">欢迎, <?php echo htmlspecialchars($_SESSION['admin_username']); ?></p>
        </div>
        
        <nav class="nav flex-column">
            <a href="index.php" class="nav-link" data-tooltip="仪表盘">
                <i class="fas fa-tachometer-alt"></i><span>仪表盘</span>
            </a>
            <a href="products.php" class="nav-link active" data-tooltip="商品管理">
                <i class="fas fa-box"></i><span>商品管理</span>
            </a>
            <a href="cdks.php" class="nav-link" data-tooltip="CDK管理">
                <i class="fas fa-gift"></i><span>CDK管理</span>
            </a>
            <a href="orders.php" class="nav-link" data-tooltip="订单管理">
                <i class="fas fa-shopping-cart"></i><span>订单管理</span>
            </a>
            <a href="payments.php" class="nav-link" data-tooltip="支付记录">
                <i class="fas fa-credit-card"></i><span>支付记录</span>
            </a>
            <a href="settings.php" class="nav-link" data-tooltip="系统设置">
                <i class="fas fa-cog"></i><span>系统设置</span>
            </a>
            <a href="logout.php" class="nav-link" data-tooltip="退出登录">
                <i class="fas fa-sign-out-alt"></i><span>退出登录</span>
            </a>
        </nav>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 页面标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-box me-2"></i>商品管理
            </h2>
            <div class="text-muted">
                <i class="fas fa-calendar me-2"></i><?php echo date('Y年m月d日 H:i:s'); ?>
            </div>
        </div>
        <?php if (isset($success)): ?>
            <div class="alert alert-success"><?php echo $success; ?></div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <!-- 添加商品表单 -->
        <div class="card">
            <div class="card-header">
                <h3 style="margin: 0;">添加新商品</h3>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="add_product">
                    <div class="form-group">
                        <label>商品名称:</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>商品描述:</label>
                        <textarea name="description" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label>价格:</label>
                        <input type="number" name="price" class="form-control" step="0.01" required>
                    </div>
                    <div class="form-group">
                        <label>库存:</label>
                        <input type="number" name="stock" class="form-control" required>
                    </div>
                    <button type="submit" class="btn btn-primary">添加商品</button>
                </form>
            </div>
        </div>
        
        <!-- 商品列表 -->
        <div class="card">
            <div class="card-header">
                <h3 style="margin: 0;">商品列表</h3>
            </div>
            <div class="card-body">
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>商品名称</th>
                            <th>价格</th>
                            <th>库存</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $product): ?>
                        <tr>
                            <td><?php echo $product['id']; ?></td>
                            <td><?php echo htmlspecialchars($product['name']); ?></td>
                            <td>¥<?php echo $product['price']; ?></td>
                            <td><?php echo $product['stock']; ?></td>
                            <td><?php echo $product['status'] ? '上架' : '下架'; ?></td>
                            <td>
                                <button class="btn btn-primary btn-sm" onclick="editProduct(<?php echo $product['id']; ?>)">编辑</button>
                                <button class="btn btn-success btn-sm" onclick="generateCDKs(<?php echo $product['id']; ?>)">生成CDK</button>
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="action" value="delete_product">
                                    <input type="hidden" name="id" value="<?php echo $product['id']; ?>">
                                    <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('确定删除这个商品吗？')">删除</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- 编辑商品模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <h3>编辑商品</h3>
            <form method="POST" id="editForm">
                <input type="hidden" name="action" value="edit_product">
                <input type="hidden" name="id" id="edit_id">
                <div class="form-group">
                    <label>商品名称:</label>
                    <input type="text" name="name" id="edit_name" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>商品描述:</label>
                    <textarea name="description" id="edit_description" class="form-control" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label>价格:</label>
                    <input type="number" name="price" id="edit_price" class="form-control" step="0.01" required>
                </div>
                <div class="form-group">
                    <label>库存:</label>
                    <input type="number" name="stock" id="edit_stock" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>状态:</label>
                    <select name="status" id="edit_status" class="form-control">
                        <option value="1">上架</option>
                        <option value="0">下架</option>
                    </select>
                </div>
                <div style="text-align: right;">
                    <button type="button" class="btn" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 生成CDK模态框 -->
    <div id="cdkModal" class="modal">
        <div class="modal-content">
            <h3>生成CDK码</h3>
            <form method="POST" id="cdkForm">
                <input type="hidden" name="action" value="generate_cdks">
                <input type="hidden" name="product_id" id="cdk_product_id">
                <div class="form-group">
                    <label>生成数量:</label>
                    <input type="number" name="count" class="form-control" value="1" min="1" max="100" required>
                </div>
                <div style="text-align: right;">
                    <button type="button" class="btn" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-success">生成</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        function editProduct(id) {
            // 通过AJAX获取商品详情
            fetch('../classes/ProductManager.php?action=get_product&id=' + id)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('edit_id').value = data.product.id;
                        document.getElementById('edit_name').value = data.product.name;
                        document.getElementById('edit_description').value = data.product.description || '';
                        document.getElementById('edit_price').value = data.product.price;
                        document.getElementById('edit_stock').value = data.product.stock;
                        document.getElementById('edit_status').value = data.product.status;
                        document.getElementById('editModal').style.display = 'block';
                    } else {
                        alert('获取商品信息失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取商品信息失败');
                });
        }
        
        function generateCDKs(productId) {
            document.getElementById('cdk_product_id').value = productId;
            document.getElementById('cdkModal').style.display = 'block';
        }
        
        function closeModal() {
            document.getElementById('editModal').style.display = 'none';
            document.getElementById('cdkModal').style.display = 'none';
        }
        
        // 点击模态框外部关闭
        window.onclick = function(event) {
            var modals = document.getElementsByClassName('modal');
            for (var i = 0; i < modals.length; i++) {
                if (event.target == modals[i]) {
                    modals[i].style.display = 'none';
                }
            }
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="assets/admin.js"></script>
</body>
</html>
